package com.frame.project.core.aspect.webaspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.frame.project.core.exception.RestResult;

/**
 * 表单验证
 * @author Administrator
 *
 */

@Aspect
@Component
public class ValidatorBeanAspect {


	@Pointcut("execution(public * com.frame.project.modules..web..*.*(..))")
	public void excudeController() {
	}


	@Around(value ="excudeController()&&args(..,bindingResult)")
	public Object validatorBeanAround(ProceedingJoinPoint pjp, BindingResult bindingResult) throws Throwable {
		Object result = null;
		//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		//HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		if (bindingResult.hasErrors()) {
			StringBuilder sBuilder = new StringBuilder();
			for (ObjectError objectError : bindingResult.getAllErrors()) {
				sBuilder.append(objectError.getDefaultMessage()+"\t");
			}
			return RestResult.genErrorResult(sBuilder.toString());
		} else {
			try{
				result = pjp.proceed(); //环绕通知必须执行，否则不进入注解的方法
			} catch (Throwable e) {
				throw e;
			}
		}
		return result;
	}




}
